package com.addplus.townmall.server.web.provider.serviceimpl.authoritymodule;

import com.addplus.townmall.server.api.constant.ErrorCode;
import com.addplus.townmall.server.api.exception.ErrorException;
import com.addplus.townmall.server.api.mapper.authority.UserMapper;
import com.addplus.townmall.server.api.model.authority.User;
import com.addplus.townmall.server.api.service.web.authoritymodule.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.RpcContext;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DefaultHashService defaultHashService;

    @Override
    public User selectByUsername(String account) {
        if (StringUtils.isBlank(account)) {
            return null;
        }
        User user = new User();
        user.setAccount(account);
        user.setIsDeleted(0);
        User userOne = userMapper.selectOne(new QueryWrapper<User>(user));
        return userOne;
    }

    @Override
    public Boolean updateLoginUser(User user) {
        User userUpdate = new User();
        userUpdate.setId(user.getId());
        userUpdate.setLoginAddress(user.getLoginAddress());
        userUpdate.setLoginCount(user.getLoginCount() + 1);
        userUpdate.setLoginTime(new Date());
        userUpdate.setGmtModified(new Date());
        int modifyUser = Integer.valueOf(RpcContext.getContext().getAttachment("id"));
        userUpdate.setModifyUser(modifyUser);
        int count = userMapper.updateById(userUpdate);
        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean addUser(User user) throws ErrorException {
        if (user == null) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        } else {
            if (StringUtils.isBlank(user.getRoles()) || StringUtils.isBlank(user.getAccount()) || StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(user.getPhone())) {
                throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
            }
        }
        user.setGmtCreate(new Date());
        user.setLoginCount(0);
        user.setIsDeleted(0);
        user.setStatus(0);
        int modifyUser =  Integer.valueOf(RpcContext.getContext().getAttachment("id"));
        user.setModifyUser(modifyUser);
        //生成加密后的密码
        HashRequest request = new HashRequest.Builder()
                .setAlgorithmName("md5").setSource(user.getPassword())
                .setSalt(ByteSource.Util.bytes(user.getAccount())).setIterations(2).build();
        String hexPassword = defaultHashService.computeHash(request).toHex();
        user.setPassword(hexPassword);
        int count = userMapper.insert(user);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Boolean deleteUserById(Integer id) throws Exception {
        if (id == null) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        } else if (id <= 0) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        User user = new User();
        user.setId(id);
        user.setIsDeleted(1);
        int modifyUser =  Integer.valueOf(RpcContext.getContext().getAttachment("id"));
        user.setModifyUser(modifyUser);
        int count = userMapper.updateById(user);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public User selectUserById(Integer id) throws Exception {
        if (id == null || id <= 0) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        User user = new User();
        user.setId(id);
        user.setIsDeleted(0);
        User userNew = userMapper.selectOne(new QueryWrapper<User>(user));
        if (userNew == null) {
            throw new ErrorException(ErrorCode.SYS_ERROR_NULLDATE);
        } else {
            if (userNew.getStatus() == 1) {
                //抛出冻结异常码
                throw new ErrorException(ErrorCode.SYS_LOGIN_MEMBER_DISABLE);
            }
        }
        return userNew;
    }

    @Override
    public User modifyUserGetInfoById(Integer id) throws Exception {
        if (id == null || id <= 0) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        User user = new User();
        user.setId(id);
        user.setIsDeleted(0);
        User userNew = userMapper.selectOne(new QueryWrapper<User>(user));
        if (userNew == null) {
            throw new ErrorException(ErrorCode.SYS_ERROR_NULLDATE);
        }
        return userNew;
    }

    @Override
    public String encryptString(User user) throws Exception {
        if (user == null) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        //生成加密后的密码
        HashRequest request = new HashRequest.Builder()
                .setAlgorithmName("md5").setSource(user.getPassword())
                .setSalt(ByteSource.Util.bytes(user.getAccount())).build();
        String hexPassword = defaultHashService.computeHash(request).toHex();
        return hexPassword;
    }

    @Override
    public Boolean updateUser(User user) throws Exception {
        if (user == null || user.getId() == null) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        user.setGmtModified(new Date());
        int modifyUser =  Integer.valueOf(RpcContext.getContext().getAttachment("id"));
        user.setModifyUser(modifyUser);
        int count = userMapper.updateById(user);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Page<User> getAllUsers(Integer pageNo, Integer pageSize) throws Exception {
        if (pageNo == null || pageSize == null) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        Page<User> page = new Page<User>(pageNo,pageSize);
        User user = new User();
        user.setIsDeleted(0);
        try {
            page = (Page<User>) userMapper.selectPage(page,new QueryWrapper<User>(user));
            if (page != null && page.getTotal()!=0) {
                return page;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        throw new ErrorException(ErrorCode.SYS_ERROR_NULLDATE);
    }

    @Override
    public User getByUser() throws Exception {
        Integer memId= Integer.valueOf(RpcContext.getContext().getAttachment("id"));
        User user = new User();
        user.setIsDeleted(0);
        user.setId(memId);
        return userMapper.selectOne(new QueryWrapper<User>(user));

    }

    @Override
    public Integer getUserNameCount(String account) throws Exception {
        if (StringUtils.isBlank(account)) {
            throw new ErrorException(ErrorCode.SYS_ERROR_PARAM);
        }
        User user = new User();
        user.setAccount(account);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        int res = userMapper.selectCount(queryWrapper);
        return res;
    }

}
